/*
 * 
 * 
 */
package de.hpi.generationmanager.tesma.data;

import de.hpi.generationmanager.tools.CSVTable;
import de.hpi.generator.config.ColumnModel;
import de.hpi.generator.config.DistributionModel;
import de.hpi.generator.config.TableModel;
import de.hpi.generator.model.Database;
import de.hpi.generator.model.Table;
import de.hpi.generator.model.TesmaColumn;
import java.util.ArrayList;

/**
 *
 * @author Michael Wolowyk
 */
public class TesmaDataTable {
    public static final String NAME_SUFFIX = "@tesma";

    CSVTable aTesmaCSVTable = null;
    Database aTesmaDataBase = null;
    Table aDBTable = null;

    protected final CSVTable getTesmaCSVTable() {
        return aTesmaCSVTable;
    }

    protected final Table getDBTable() {
        return aDBTable;
    }
    
    public TesmaDataTable(CSVTable aTesmaCSVTable, Database aTesmaDataBase) {
        this.aTesmaCSVTable = aTesmaCSVTable;
        this.aTesmaDataBase = aTesmaDataBase;
        aDBTable = new Table(getModel(), aTesmaDataBase);
    }

    protected final TableModel getModel() {
        return new TableModel(aTesmaCSVTable.getName().replace(".csv", NAME_SUFFIX), 0);
    }

    public void loadDataInToColumns() throws Exception {
        aTesmaCSVTable.openForRead();
        TesmaColumnsCollection aColumns = createColumns();
        aColumns.clean();
        aColumns.openForAppend();
        ArrayList<Integer> aRowCells = null;
        while ((aRowCells = aTesmaCSVTable.readNextRowDataAsIntegers()) != null) {
            aColumns.distributeData(aRowCells);
        }
        aColumns.closeAfterAppend();
        aTesmaCSVTable.closeAfterRead();
    }

    public static ArrayList<TesmaDataTable> findTesmaDataTables(String aTesmaDataPath, Database aTesmaDataBase) throws Exception {
        ArrayList<TesmaDataTable> result = new ArrayList<TesmaDataTable>();

        for (CSVTable aTesmaTableFile : CSVTable.findTables(aTesmaDataPath)) {
            result.add(new TesmaDataTable(aTesmaTableFile, aTesmaDataBase));
        }

        return result;
    }

    protected TesmaColumnsCollection createColumns() throws Exception {
        TesmaColumnsCollection result = new TesmaColumnsCollection(aDBTable);

        for (String aColumnName : aTesmaCSVTable.readHeader()) {
            TesmaColumn aNewColumn = new TesmaColumn(new ColumnModel(aColumnName, 0, "TesmaData", new DistributionModel("ZERO", "")), aDBTable);
            aDBTable.getColumns().add(aNewColumn);
            result.add(aNewColumn);
        }

        return result;
    }
}
